<template>
	<a-modal :visible="visible" title="修改密码" width="600px" centered @cancel="dialogClose">
		<a-form ref="form" :model="formState" name="reset" :rules="rules">
			<a-form-item label="企业码" name="shopNo">
				<template v-if="enterprise?.no">{{ enterprise?.no }}</template>
				<a-input v-else v-model:value="formState.shopNo" placeholder="请输入企业代码" :maxlength="30" />
			</a-form-item>
			<a-form-item label="手机号" name="account">
				<template v-if="currentUser.phone">{{ currentUser.phone }}</template>
				<a-input v-else v-model:value="formState.account" placeholder="请输入手机号" :maxlength="11" />
			</a-form-item>
			<a-form-item name="verified" :wrapper-col="{offset: 3}">
				<slide-verify :w="483" slider-text="向右滑动" ref="verifyBlock" :imgs="verifyImgs" @again="onAgain" @success="onSuccess" @fail="onFail" @refresh="onRefresh" />
				<template v-if="formState.verified" #help>
					{{ verifyMsg }}
				</template>
			</a-form-item>
			<a-form-item label="验证码" name="verifyCode">
				<a-row :gutter="10">
					<a-col flex="1">
						<a-input v-model:value="formState.verifyCode" placeholder="请输入验证码" :maxlength="6" />
					</a-col>
					<a-col>
						<a-button :disabled="countdown > 0 || !formState.verified" type="primary" @click="getVerification">
							{{ countdown === 0 ? '发送验证码' : `${countdown}秒后重新获取` }}
						</a-button>
					</a-col>
				</a-row>
			</a-form-item>
			<a-form-item label="新密码" name="password">
				<a-input-password v-model:value="formState.password" placeholder="6～16位字符，密码由字母 + 数字组合" :maxlength="16" autocomplete="new-password" />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button type="primary" @click="submitForm">保存</a-button>
		</template>
	</a-modal>
</template>
<script lang="ts" setup>
	import SlideVerify, {SlideVerifyInstance} from 'vue3-slide-verify'
	import 'vue3-slide-verify/dist/style.css'
	import type {Rule} from 'ant-design-vue/es/form'
	import {reactive, ref} from 'vue'
	import {message} from 'ant-design-vue'
	import {useStore} from '@/store/index'
	import {validatePassword, validatePhone, validateVerifyCodes} from '@/utils/yuxin-main/formValidation'
	import {sendMessage} from '@/api/yuxin-main/user'
	import {FormExpose} from 'ant-design-vue/lib/form/Form'
	import XEUtils from 'xe-utils'

	const store = useStore()

	const props = defineProps({
		visible: Boolean
	})

	const { currentUser, enterprise }: any = store

	interface FormState {
		account: string
		verified: boolean
		verifyCode: string
		password: string,
		shopNo: string
	}

	const formState = reactive<FormState>({
		account: currentUser.phone,
		verified: false,
		verifyCode: '',
		password: '',
		shopNo: enterprise?.no
	})

	const form = ref<FormExpose>()
	const verifyBlock = ref<SlideVerifyInstance>()
	const verifyMsg = ref<string>('请先验证')
	const countdown = ref<number>(0)
	// 在线随机图片
	const verifyImgs = new Array(10).fill(1).map(() => `https://infinitypro-img.infinitynewtab.com/wallpaper/nature/${XEUtils.random(100, 5000)}.jpg?imageView2/2/w/500/format/webp/interlace/1`)

	const rules: Record<string, Rule[]> = {
		account: [{required: true, validator: validatePhone}],
		shopNo: [{ required: true }],
		verified: [
			{
				validator: (_rule: Rule, value: string) => {
					return new Promise<void>((resolve, reject) => {
						value ? resolve() : reject(verifyMsg.value)
					})
				}
			}
		],
		verifyCode: [{required: true, validator: validateVerifyCodes}],
		password: [{required: true, validator: validatePassword}]
	}

	const onAgain = () => {
		formState.verified = false
		verifyMsg.value = '检测到非人为操作的哦！重新再来'
		form.value?.validate('verified')
		// 刷新
		verifyBlock.value?.refresh()
	}

	/**
	 *滑动成功
	 * @param times 运行时间
	 */
	const onSuccess = (times: number) => {
		formState.verified = true
		form.value?.validate('verified')
		verifyMsg.value = `验证通过, 耗时${(times / 1000).toFixed(1)}s`
	}

	/**
	 * 滑块验证失败
	 */
	const onFail = () => {
		formState.verified = false
		verifyMsg.value = '验证不通过，请重新验证'
		form.value?.validate('verified')
	}

	/**
	 * 重置滑块
	 */
	const onRefresh = () => {
		verifyMsg.value = '请先验证'
		formState.verified = false
		form.value?.clearValidate('verified')
	}

	/**
	 * 提交请求修改密码
	 */
	const submitForm = () => {
		form.value
			?.validate()
			.then(() => {
				store.changePassword(formState)
			})
			.catch(err => {
				console.log('error', err)
			})
	}

	/**
	 *
	 * 倒计时
	 * @param value
	 */
	const counter = (value: number) => {
		countdown.value = value
		const timer = setInterval(() => {
			if (countdown.value === 0) {
				clearInterval(timer)
			} else {
				countdown.value--
			}
		}, 1000)
	}

	/**
	 * 发送验证码
	 */
	const getVerification = () => {
		const phone = currentUser.phone || formState.account
		const shopNo = formState.shopNo
		sendMessage({ mobile: phone, shopNo }).then(res => {
			counter(60)
			message.success('短信发送成功，请注意接收！')
		})
	}

	const emits = defineEmits(['update:visible'])

	/**
	 * 关闭右上角按钮回调
	 */
	const dialogClose = () => {
		form.value?.resetFields()
		verifyMsg.value = '请先验证'
		verifyBlock.value?.refresh()
		emits('update:visible', false)
	}
</script>
